<?php

declare(strict_types=1);

namespace App\Controller\Safepay\V2\Shop;

use App\Controller\Safepay\V2\Controllers;
use App\Exception\InternalException;
use App\Request\Shop\Shop as ShopRequest;
use App\Services\Shop\Shop as ShopServices;
use Hyperf\DbConnection\Db;
use Psr\Http\Message\ResponseInterface;
use App\Services\App\App as AppServices;

/**
 * 店铺管理
 * @author zx
 * @package App\Controller\Api\V2\Shop
 */
class Shop extends Controllers
{
    /**
     * 请求类
     * @var string
     */
    protected string $requestClass = ShopRequest::class;

    public function __construct(
        ShopServices $shopServices,
        protected AppServices $appServices
    )
    {
        parent::__construct();
        $this->services = $shopServices;
    }

    /**
     * 新增
     * @return ResponseInterface
     */
    public function save():ResponseInterface
    {
        $input = $this->input(['name', 'app_id', 'app_secret', 'payment_notify']);

        Db::transaction(function () use ($input) {
            /** @var \App\Model\Shop\Shop $model */
            $model = $this->services->create($input);
            if (!$model->exists) {
                throw new InternalException();
            }
            $input['app_name'] = $input['name'];
            $appModel = $model->app()->create($input);
            if (!$appModel->exists) {
                throw new InternalException();
            }
        });

        return stored();
    }

    /**
     * 编辑
     * @return ResponseInterface
     * @throws \Throwable
     */
    public function update():ResponseInterface
    {
        $input = $this->input(['app_id', 'app_secret', 'payment_notify', 'status']);

        $model = $this->appServices->where('app_id', $input['app_id'])->firstOrFail();
        if (!$model->fill($input)->save()) {
            return internalError();
        }

        return updated();
    }
}
